package br.ufrj.neg.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.bean.Idioma;
import br.ufrj.neg.servlet.PageContext;

public class VelocityRender extends VelocityViewServlet {

	public void doRequest(HttpServletRequest request, HttpServletResponse response)  throws IOException{
        Context context = null;
        
        try
        {
        	
        	if( request.getAttribute("idioma")==null){
        	
        		HttpSession session = request.getSession();
        		Idioma idioma = null;
        		String idioma_setado = null;        		
        		        		
        		try {
        			//Este atributo eh setado em IdiomaSwitcher.java
        			idioma_setado = session.getAttribute("idioma_setado").toString();	
        			idioma = new Idioma( idioma_setado );			
        		} catch (Exception e) {
        			if( request.getHeader("Accept-Language")!=null ){				
        				idioma = new Idioma( request.getHeader("Accept-Language").split(";")[0].split(",")[0] );	
        			}
        			else{
        				idioma = new Idioma( "en-US" );
        			}
        		}
        		
        		request.setAttribute("idioma", idioma);		        		
        		
        		
        	}
        	
            // then get a context
            context = createContext(request, response);

            // call standard extension point
            fillContext(context, request);
            context.put("pageContext", new PageContext(request));

            setContentType(request, response);

            // get the template
            Template template = handleRequest(request, response, context);

            // merge the template and context into the response
            mergeTemplate(template, context, response);
        } catch (IOException e) {
            error(request, response, e);
            throw e;
        }
        catch (ResourceNotFoundException e)
        {
            manageResourceNotFound(request, response, e);
        }
        catch (RuntimeException e)
        {
            error(request, response, e);
            throw e;
        }
        finally
        {
            requestCleanup(request, response, context);
        }				
	}
	
	
}
